package com.ruoyi.wxLockApi.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.lock.domain.ACheckaIn;
import com.ruoyi.lock.domain.ALogs;
import com.ruoyi.lock.domain.AWaringInfo;
import com.ruoyi.lock.mapper.AWaringInfoMapper;
import com.ruoyi.lock.mapper.AWechatOfficialAccountUsersMapper;
import com.ruoyi.lock.service.IACheckaInService;
import com.ruoyi.lock.service.IALogsService;
import com.ruoyi.lock.service.IAWaringInfoService;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.mapper.SysNoticeMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.websocket.service.WebSocketService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 微信
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/weixin/dept")
@Anonymous
public class WeiXinController extends BaseController
{
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private AWechatOfficialAccountUsersMapper wechatOfficialAccountUsersMapper;

    @Autowired
    private SysNoticeMapper sysNoticeMapper;
    @Autowired
    private AWaringInfoMapper aWaringInfoMapper;
    @Autowired
    private IACheckaInService aCheckaInService;
    @Autowired
    private IALogsService iaLogsService;

    @Autowired
    private IAWaringInfoService aWaringInfoService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private WebSocketService webSocketService;

    /**
     * 获取部门列表
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public AjaxResult list(SysDept dept)
    {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable Long deptId)
    {
        deptService.checkDeptDataScope(deptId);
        return success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept)
    {
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(getUsername());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept)
    {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        else if (dept.getParentId().equals(deptId))
        {
            return error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0)
        {
            return error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(getUsername());

        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
//    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return warn("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return warn("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 查询上级小区
     */
    @GetMapping("/getParent")
    public TableDataInfo selectParent(SysDept sysDept){
        List<SysDept> sysDepts = deptService.selectParent(sysDept);

        return getDataTable(sysDepts);
    }

    /**
     *
     */
    @GetMapping("/selectParentFindInSet")
    public TableDataInfo selectParentFindInSet(SysDept sysDept){
        List<SysDept> sysDepts = deptService.selectParentFindInSet(sysDept);

        return getDataTable(sysDepts);
    }

    /**
     * 根据楼栋查询楼层
     */
//    @GetMapping("/getLouCeng")
//    public TableDataInfo listLCHByLouDong(ABuildFrameworkRoom aBuildFrameworkRoom)
//    {
//        List<ABuildFrameworkRoom> list = aBuildFrameworkRoomService.listLCHByLouDong(aBuildFrameworkRoom);
//        return getDataTable(list);
//    }
//
//    /**
//     * 根据楼层查房间
//     */
//    @GetMapping("/getFangJian")
//    public TableDataInfo listFJByLouCeng(ABuildFrameworkRoom aBuildFrameworkRoom)
//    {
//        List<ABuildFrameworkRoom> list = aBuildFrameworkRoomService.listFJByLouCeng(aBuildFrameworkRoom);
//        return getDataTable(list);
//    }
//
//    /**
//     * 新增租户
//     */
//    @PostMapping("/addBasicTenant")
//    public AjaxResult addBasicTenant(@RequestBody ATenant aTenant) {
//        //新增查关注
//        AWechatOfficialAccountUsers aWechatOfficialAccountUsers = wechatOfficialAccountUsersMapper.selectAWechatOfficialAccountUsersByUniCode(aTenant.getUniCode());
//        if(aWechatOfficialAccountUsers == null){
//            return AjaxResult.error("请先点击顶层公众号！");
//        }
//        int i = aTenantService.insertATenant(aTenant);
//
//        return toAjax(i);
//    }
//
//    /**
//     * 查询租户信息列表
//     */
////    @PreAuthorize("@ss.hasPermi('lock:tenant:list')")
//    @GetMapping("/listAenAnt")
//    public TableDataInfo list(ATenant aTenant) {
//        startPage();
//        List<ATenant> list = aTenantService.selectATenantList2(aTenant);
//        return getDataTable(list);
//    }
//
//
//    /*
//    * 获取锁的信息
//    * */
//    @GetMapping("/getLock")
//    public AjaxResult getLock(AKey aKey)
//    {
////        AKey aKey1 = aKeyMapper.selectAKeyGet(aKey.getUniCode());
//        List<AKey> aKey1 = aKeyMapper.selectAKeyGetLIst(aKey.getUniCode());
//        if(aKey1 != null && !aKey1.isEmpty()){
//            ASmartlocks aSmartlocks = aSmartlocksMapper.selectASmartlocksByLockMac(aKey1.get(0).getLockMac());
//            aKey1.get(0).setASmartlocks(aSmartlocks);
//        }
//        return AjaxResult.success(aKey1);
//    }
//    /*
//    * 公告信息
//    * */
//    @GetMapping("/getNoticeLists")
//    public TableDataInfo getNoticeLists(AKey aKey)
//    {
//        ATenant aTenant = aTenantMapper.selectATenantByuniCode(aKey.getUniCode());
//        SysNotice sysNotice = new SysNotice();
////        sysNotice.setDeptId(aTenant.getCellid());
//        List<SysNotice> sysNotices = sysNoticeMapper.selectNoticeList(sysNotice);
//
//        return getDataTable(sysNotices);
//    }
//


    /**
     * 新增故障信息
     */
//    @PostMapping("/addReport")
//    @Anonymous
//    public AjaxResult add(@RequestBody AWaringInfo aWaringInfo)
//    {
//        ATenant aTenant = aTenantMapper.selectATenantByuniCode(aWaringInfo.getUnionid());
//        aWaringInfo.setAgentsid(aTenant.getAgentsid());
//        aWaringInfo.setCellid(aTenant.getCellid());
//        aWaringInfo.setLdid(aTenant.getLdid());
//        aWaringInfo.setLcid(aTenant.getLcid());
//        aWaringInfo.setRoomid(Long.valueOf(aTenant.getRoomId()));
////        aWaringInfo.setRoomid(aTenant.getRoomid());
//        aWaringInfo.setCreateTime(new Date());
//
//        SysUser sysUser = new SysUser();
//        sysUser.setDeptId(aTenant.getAgentsid());
//        List<SysUser> sysUsers = sysUserMapper.selectUserList(sysUser);
//
//        for (SysUser user : sysUsers) {
//            JSONObject json = new JSONObject();
//            json.put("code",0);
//            json.put("msg",aWaringInfo.getRemark());
//            json.put("type",1);
//            webSocketService.sendMessageByUserId(user.getUserId(),json);
//        }
//        return toAjax(aWaringInfoMapper.insertAWaringInfo(aWaringInfo));
//    }

    /**
     * 查询公告信息
     */
    @GetMapping("/getReport")
    public TableDataInfo getReport(SysNotice sysNotice)
    {
        //分页
        PageHelper.startPage(sysNotice.getPageNum(),sysNotice.getPageSize()).setReasonable(false);
        return getDataTable(sysNoticeMapper.selectNoticeList(sysNotice));
    }

    /**
     * 查询故障信息
     */
    @GetMapping("/getGuZhang")
    public TableDataInfo getGuZhang(AWaringInfo aWaringInfo)
    {
//        ATenant aTenant = aTenantMapper.selectATenantByuniCode(aWaringInfo.getUnionid());
//        aWaringInfo.setCellid(aTenant.getCellid());
        //分页
        PageHelper.startPage(aWaringInfo.getPageNum(),aWaringInfo.getPageSize()).setReasonable(false);
        List<AWaringInfo> aWaringInfos = aWaringInfoMapper.selectAWaringInfoList(aWaringInfo);
        return getDataTable(aWaringInfos);
    }

    /**
     * 查询打卡记录
     */
//    @PreAuthorize("@ss.hasPermi('lock:in:list')")
    @GetMapping("/checkAInList")
    public TableDataInfo checkAInList(ACheckaIn aCheckaIn)
    {
        PageHelper.startPage(aCheckaIn.getPageNum(),aCheckaIn.getPageSize()).setReasonable(false);
//        startPage();
        List<ACheckaIn> list = aCheckaInService.checkAInList(aCheckaIn);
        return getDataTable(list);
    }

    /**
     * 查询开锁日志
     */
//    @PreAuthorize("@ss.hasPermi('lock:logs:list')")
    @GetMapping("/getLogsList1")
    public TableDataInfo getLogsList1(ALogs aLogs)
    {
        PageHelper.startPage(aLogs.getPageNum(),aLogs.getPageSize()).setReasonable(false);
//        startPage();
        List<ALogs> list = iaLogsService.selectALogsList1(aLogs);
        return getDataTable(list);
    }

    /**
     * 新增打卡
     */
//    @PreAuthorize("@ss.hasPermi('lock:in:add')")
    @Log(title = "打卡", businessType = BusinessType.INSERT)
    @PostMapping("/checkaInAdd")
    @RepeatSubmit
    public AjaxResult checkaInAdd(@RequestBody ACheckaIn aCheckaIn)
    {
        return toAjax(aCheckaInService.insertACheckaIn(aCheckaIn));
    }


}
